/*
 * Copyright 2005-2013 rzico.com. All rights reserved.
 * Support: http://www.rzico.com
 * License: http://www.rzico.com/license
 */
package com.rzico.core.plugin.oss;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;

import com.rzico.core.entity.SysPlugin;
import com.rzico.core.model.PluginAttribute;
import com.rzico.core.plugin.StoragePlugin;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;

/**
 * Plugin - 本地文件存储
 * 
 * @author SHOP++ Team
 * @version 3.0
 */
@Component("filePlugin")
public class FilePlugin extends StoragePlugin implements ServletContextAware {

	/** servletContext */
	private ServletContext servletContext;

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	@Override
	public String getName() {
		return "本地文件存储";
	}

	@Override
	public String getVersion() {
		return "1.0";
	}


	@Override
	public List<PluginAttribute> getAttributeKeys() {
		List<PluginAttribute> data = new ArrayList<>();
		data.add(new PluginAttribute("dir","dir",PluginAttribute.STRING_VALUE));
		data.add(new PluginAttribute("urlPrefix","urlPrefix",PluginAttribute.STRING_VALUE));

		return data;
	}

	//获取流文件
	private static void inputStreamToFile(InputStream ins, File file) {
		try {
			OutputStream os = new FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void upload(SysPlugin sysPlugin, String path, MultipartFile file, String contentType) throws IOException {
		File destFile = new File(sysPlugin.getAttribute("dir")+ StringUtils.removeStart(path, "/"));
		try {
			if (!destFile.exists()) {
				destFile.mkdirs();
			}
			InputStream ins = null;
			ins = file.getInputStream();
			inputStreamToFile(ins, destFile);
			ins.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}